package com.suray.wcs.web.system.controller;

import com.suray.commin.annotation.Log;
import com.suray.commin.core.controller.BaseController;
import com.suray.commin.core.controller.ResponseData;
import com.suray.commin.core.utils.StringUtils;
import com.suray.commin.core.utils.UserConstants;
import com.suray.commin.enmus.BusinessType;
import com.suray.commin.core.utils.SecurityUtils;
import com.suray.commin.core.entity.DepartmentDB;
import com.suray.wcs.service.system.service.impl.DepartmentDBServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;


@RequiresAuthentication
@RestController
@Api(tags = "部门接口")
@RequestMapping("/dept")
@CrossOrigin
public class DepartmentDBController extends BaseController {


    @Autowired
    private DepartmentDBServiceImpl deptService;

    /**
     * 获取部门列表
     */
    @ApiOperation(value = "获取部门列表")
    @PreAuthorize("@ss.hasPermi('dept:list')")
    @GetMapping("/list")
    public ResponseData list(DepartmentDB dept) {
        List<DepartmentDB> depts = deptService.selectDeptList(dept);
        return ResponseData.success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @ApiOperation(value = "查询部门列表（排除节点）")
    @PreAuthorize("@ss.hasPermi('dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public ResponseData excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<DepartmentDB> depts = deptService.selectDeptList(new DepartmentDB());
        Iterator<DepartmentDB> it = depts.iterator();
        while (it.hasNext()) {
            DepartmentDB d = (DepartmentDB) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        return ResponseData.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @ApiOperation(value = "根据部门编号获取详细信息")
    @GetMapping(value = "/{deptId}")
    public ResponseData getInfo(@PathVariable Long deptId) {
        return ResponseData.success(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @ApiOperation(value = "获取部门下拉树列表")
    @GetMapping("/treeselect")
    public ResponseData treeselect(DepartmentDB dept) {
        List<DepartmentDB> depts = deptService.selectDeptList(dept);
        return ResponseData.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @ApiOperation(value = "加载对应角色部门列表树")
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public ResponseData roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
        List<DepartmentDB> depts = deptService.selectDeptList(new DepartmentDB());
        ResponseData ajax = ResponseData.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * 新增部门
     */
    @ApiOperation(value = "新增部门")
    @PreAuthorize("@ss.hasPermi('dept:add')")
    @Log(title = "部门管理", method = "新增部门", businessType = BusinessType.INSERT)
    @PostMapping
    public ResponseData add(@Validated @RequestBody DepartmentDB dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return ResponseData.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @ApiOperation(value = "修改部门")
    @PreAuthorize("@ss.hasPermi('dept:edit')")
    @Log(title = "部门管理", method = "修改部门", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResponseData edit(@Validated @RequestBody DepartmentDB dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return ResponseData.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return ResponseData.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return ResponseData.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @ApiOperation(value = "删除部门")
    @PreAuthorize("@ss.hasPermi('dept:remove')")
    @Log(title = "部门管理", method = "删除部门", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public ResponseData remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return ResponseData.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return ResponseData.error("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }
}